package com.qcs.sleep.warn;

import com.qcs.sleep.OnWarnListener;
import com.qcs.sleep.helper.DateFormatHelper;
import com.qcs.sleep.log.Log4J;
import com.qcs.sleep.service.Action;

/**
 * Created by chshqiang on 13-10-17.
 * 夜晚休息模式
 */
public class NightWarnAdapter implements WarnAdapter {
    private final int FIRST_TIME_DELAY = 10 * 60; // 初始警示时间间隔，为600个时间单位

    private OnWarnListener mListener;

    private int nextWarnLength = FIRST_TIME_DELAY; // 下一次示警长度，初始值为FIRST_TIME_DELAY
    private int currentWarnLength = 0;

    @Override
    public void run() {
        if (isGoodNight() && isRoutineWarn() && null != mListener) {
            mListener.onWarn(60, OnWarnListener.FLAG_ACTIVITY, null);
            reset();
        }
    }

    private boolean isGoodNight() { // 是否已经达到睡觉时间点
        final int MIN_STARTING_TIME = 2130; // 进入夜晚模式的最小时间点
        final int MAX_STARTING_TIME = 2330; // 进入夜晚模式的最大时间点
        final int END_STARTING_TIME = 530; // 进入夜晚模式的最后时间点

        int time = DateFormatHelper.instance().format(System.currentTimeMillis());

        boolean isTimeout = time > MIN_STARTING_TIME || time < END_STARTING_TIME;

        if (isTimeout && 0 == currentWarnLength) // 已经时间警言点且暂未示警后的处理
            if (MAX_STARTING_TIME < time || time < END_STARTING_TIME) { // 晚上11:30之后
                nextWarnLength = 60;
            } else if (2230 < time) { // 晚上10:30之后
                nextWarnLength = 3 * 60;
            } else if (MIN_STARTING_TIME < time) { // 晚上10:00之后
                nextWarnLength = 5 * 60;
            }

        return isTimeout; // 常规警示时间段：21点30分到次日5点30分
    }

    private boolean isRoutineWarn() { // 常规示警的算法
        int ROUTINE_WARN_MIN_DELAY = 20; // 常规警示的最小间隔

        Log4J.m("currentWarnLength: " + currentWarnLength + ", nextWarnLength: " + nextWarnLength);
        if (0 == currentWarnLength) { // 表示第一次进入警示进程时，进入干扰进程。
            return true;
        }

        currentWarnLength++;
        if (currentWarnLength > nextWarnLength) {

            if (ROUTINE_WARN_MIN_DELAY >= nextWarnLength) {
                // 单位：TIME_UNIT，下一次示警时间不大于ROUTINE_WARN_MIN_DELAY个单位时间后，则固定为ROUTINE_WARN_MIN_DELAY。
                nextWarnLength = ROUTINE_WARN_MIN_DELAY;
            } else { // 未达到最小间隔时，下次间隔时间为当前间隔时间减去六分之一
                nextWarnLength -= nextWarnLength / 6;
            }

            return true;
        }

        return false;
    }

    private void reset() {
        currentWarnLength = 1;
    }

    @Override
    public void onReceive(String action) {
        if (Action.RUN.equals(action)) {
            reset();
        }
    }

    @Override
    public void setOnWarnListener(OnWarnListener listener) {
        mListener = listener;
    }
}
